import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'  // 修改这一行：从命名导入改为默认导入
import { getUser } from '@/lib/authUtils'

// 获取单个课程详情
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
): Promise<NextResponse> {
  try {
    const userId = await getUser(request)
    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const course = await prisma.vms_course.findFirst({
      where: {
        id: params.id,
        user_id: userId.toString()
      },
      include: {
        sections: {
          include: {
            source_copy: true
          },
          orderBy: {
            order: 'asc'
          }
        },
        participants: {
          orderBy: {
            joined_at: 'desc'  // 将 created_at 改为 joined_at
          }
        },
        _count: {
          select: {
            access_logs: true
          }
        }
      }
    })

    if (!course) {
      return NextResponse.json({ error: 'Course not found' }, { status: 404 })
    }

    return NextResponse.json(course)
  } catch (error) {
    console.error('Error fetching course:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}

// 更新课程
export async function PUT(request: Request, { params }: { params: { id: string } }) {
  try {
    const body = await request.json();
    const {
      title,
      description,
      cover_image,
      is_free,              // 修改：从 is_public 改为 is_free
      max_participants,
      start_time,
      end_time,
      access_password,
      status
    }: {
      title?: string;
      description?: string;
      cover_image?: string;
      is_free?: boolean;    // 修改：从 is_public 改为 is_free
      max_participants?: number;
      start_time?: string;
      end_time?: string;
      access_password?: string;
      status?: string;
    } = body;

    const updateData: any = {};
    if (title !== undefined) updateData.title = title;
    if (description !== undefined) updateData.description = description;
    if (cover_image !== undefined) updateData.cover_image = cover_image;
    if (is_free !== undefined) updateData.is_free = is_free;  // 修改：从 is_public 改为 is_free
    if (max_participants !== undefined) updateData.max_participants = max_participants;
    if (start_time !== undefined) updateData.start_time = new Date(start_time);
    if (end_time !== undefined) updateData.end_time = new Date(end_time);
    if (access_password !== undefined) updateData.access_password = access_password;
    if (status !== undefined) updateData.status = status;

    const course = await prisma.vms_course.update({
      where: { id: params.id },
      data: updateData
    });

    return NextResponse.json(course);
  } catch (error) {
    console.error('Error updating course:', error);
    return NextResponse.json({ error: 'Failed to update course' }, { status: 500 });
  }
}

// 删除课程
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
): Promise<NextResponse> {
  try {
    const userId = await getUser(request)
    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const deletedCourse = await prisma.vms_course.deleteMany({
      where: {
        id: params.id,
        user_id: userId.toString()
      }
    })

    if (deletedCourse.count === 0) {
      return NextResponse.json({ error: 'Course not found' }, { status: 404 })
    }

    return NextResponse.json({ message: 'Course deleted successfully' })
  } catch (error) {
    console.error('Error deleting course:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}